#include "StreamSource.h"
#include <cstdlib>
#include <cstdio>
#include <iostream>

StreamSource::StreamSource() : m_data(new char[SIZE]), m_scratch(new char[SIZE]) {
}

void StreamSource::feedTo(Sink<StringPiece> *sink) {
    int writePos = 0;
    int readPos  = 0;
    bool ignoring = false;
/*
    while (true) {
        feedOne:
        while(true) {
            for(int i = readPos; i < writePos; ++i) {
                if(m_data[i] == '\n') {
                    // feed
                    if(!ignoring) {
                        sink->process(StringPiece(m_data + readPos, i - readPos - 1));
                    }
                    readPos = i + 1;
                    ignoring = false;
                    goto feedOne;
                }
            }
            if(writePos < SIZE) {
                int n = read(fileno(stdin), m_data + writePos, SIZE - writePos);
                if(n <= 0) {
                    goto end;
                }
            } else if(readPos == 0) {
                if(!ignoring) {
                    sink->process(StringPiece(m_data, SIZE));
                    ignoring = true;
                }
                readPos = writePos = 0;
            } else {
                int len = writePos - readPos;
                memcpy(m_scratch, m_data + readPos, writePos - readPos);

                char *tmp = m_scratch;
                m_scratch = m_data;
                m_data = tmp;

                readPos = 0;
                writePos = len;
            }
        }
    }
    end: */
    int n = -1;
    while ((n = read(fileno(stdin), m_data, SIZE)) > 0) {
        sink->process(StringPiece(m_data, SIZE));
    }

    sink->finish();

    return;
}

